

package com.maoshi.shop.seckill.multishop.controller;

import cn.hutool.core.util.StrUtil;
import com.maoshi.shop.bean.enums.OfflineHandleEventType;
import com.maoshi.shop.bean.enums.ProdType;
import com.maoshi.shop.bean.model.OfflineHandleEvent;
import com.maoshi.shop.bean.model.Product;
import com.maoshi.shop.bean.param.OfflineHandleEventAuditParam;
import com.maoshi.shop.bean.param.ProductParam;
import com.maoshi.shop.common.enums.MaoshiHttpStatus;
import com.maoshi.shop.common.exception.MaoshiShopBindException;
import com.maoshi.shop.seckill.multishop.dto.SeckillProdDto;
import com.maoshi.shop.seckill.multishop.param.SeckillParam;
import com.maoshi.shop.seckill.comment.model.Seckill;
import com.maoshi.shop.seckill.comment.model.SeckillSku;
import com.maoshi.shop.seckill.comment.service.SeckillService;
import com.maoshi.shop.common.annotation.SysLog;

import javax.validation.Valid;

import com.maoshi.shop.seckill.comment.service.SeckillSkuService;
import com.maoshi.shop.security.multishop.util.SecurityUtils;
import com.maoshi.shop.service.OfflineHandleEventService;
import com.maoshi.shop.service.ProductService;
import ma.glasnost.orika.MapperFacade;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import lombok.AllArgsConstructor;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.maoshi.shop.common.util.PageParam;
import com.baomidou.mybatisplus.core.metadata.IPage;

import java.util.List;
import java.util.Objects;


/**
 * 秒杀信息
 *
 * @author LGH
 * @date 2019-08-28 09:36:59
 */
@RestController
@AllArgsConstructor
@RequestMapping("/seckill/seckill")
public class SeckillController {

    private final SeckillService seckillService;

    private final MapperFacade mapperFacade;

    private final ProductService productService;

    private final SeckillSkuService seckillSkuService;

    private final OfflineHandleEventService offlineHandleEventService;

    /**
     * 分页查询
     *
     * @param page    分页对象
     * @param seckill 秒杀信息
     * @return 分页数据
     */
    @GetMapping("/page")
    public ResponseEntity<IPage<Seckill>> getSeckillPage(PageParam<Seckill> page, Seckill seckill) {
        return ResponseEntity.ok(seckillService.page(page, new LambdaQueryWrapper<Seckill>()
                .eq(seckill.getStatus() != null,Seckill::getStatus,seckill.getStatus())
                .eq(Seckill::getShopId, SecurityUtils.getShopUser().getShopId())
                .eq(Seckill::getIsDelete, 0)
                .orderByDesc(Seckill::getSeckillId)
        ));
    }


    /**
     * 通过id查询秒杀信息
     *
     * @param seckillId id
     * @return 单个数据
     */
    @GetMapping("/info/{seckillId}")
    public ResponseEntity<SeckillProdDto> getById(@PathVariable("seckillId") Long seckillId) {
        Seckill seckill = seckillService.getSeckillById(seckillId);

        SeckillProdDto dto = new SeckillProdDto();
        dto.setSeckill(seckill);
        Product product = productService.getProductByProdId(seckill.getProdId());
        dto.setProd(product);

        dto.setSeckillSkus(seckillSkuService.listSeckillSkuBySeckillId(seckillId));

        return ResponseEntity.ok(dto);
    }

    /**
     * 新增秒杀信息
     *
     * @param seckillParam 秒杀信息
     * @return 是否新增成功
     */
    @SysLog("新增秒杀信息")
    @PostMapping
    public ResponseEntity<Void> save(@RequestBody @Valid SeckillParam seckillParam) {

        Seckill seckill = mapperFacade.map(seckillParam, Seckill.class);
        Integer prodCount = productService.count(new LambdaQueryWrapper<Product>()
                .eq(Product::getShopId, SecurityUtils.getShopUser().getShopId())
//                .and(wrapper -> wrapper.isNull(Product::getGroupActivityId).or().eq(Product::getGroupActivityId, 0))
//                .and(wrapper -> wrapper.isNull(Product::getSeckillActivityId).or().eq(Product::getSeckillActivityId, 0))
                .and(wrapper -> wrapper.isNull(Product::getProdType).or().eq(Product::getProdType, ProdType.PROD_TYPE_NORMAL))
                .eq(Product::getProdId, seckillParam.getProdId()));

        if (prodCount == 0) {
            throw new MaoshiShopBindException("商品无法参与秒杀活动");
        }

        List<SeckillSku> seckillSkus = seckillParam.getSeckillSkus();

        Integer seckillTotalStocks = 0;

        Double seckillPrice = Double.MAX_VALUE;


        for (SeckillSku seckillSku : seckillSkus) {

            seckillTotalStocks += seckillSku.getSeckillStocks();

            seckillPrice = Math.min(seckillPrice, seckillSku.getSeckillPrice());
        }


        // 库存
        seckill.setSeckillOriginStocks(seckillTotalStocks);
        seckill.setSeckillTotalStocks(seckillTotalStocks);
        // 配置店铺id
        seckill.setShopId(SecurityUtils.getShopUser().getShopId());
        seckill.setProdId(seckillParam.getProdId());
        seckill.setSeckillPrice(seckillPrice);
        seckillService.saveSeckill(seckill, seckillSkus);

        // 清除缓存
        productService.removeProductCacheByProdId(seckillParam.getProdId());
        seckillSkuService.removeSeckillSkuCacheBySeckillId(seckill.getSeckillId());
        seckillService.removeSeckillCacheById(seckill.getSeckillId());
        return ResponseEntity.ok().build();
    }

    /**
     * 查询可以参与秒杀的商品
     */
    @GetMapping("/canSekcillProdPage")
    public ResponseEntity<IPage<Product>> page(PageParam<Product> page, ProductParam product) {
        IPage<Product> products = productService.page(page,
                new LambdaQueryWrapper<Product>()
                        .eq(Product::getStatus, 1)
                        .eq(Product::getShopId, SecurityUtils.getShopUser().getShopId())
                        .eq(product.getShopCategoryId() != null, Product::getShopCategoryId, product.getShopCategoryId())
                        .like(StrUtil.isNotBlank(product.getProdName()), Product::getProdName, product.getProdName())
//                        .and(wrapper -> wrapper.isNull(Product::getGroupActivityId).or().eq(Product::getGroupActivityId, 0))
//                        .and(wrapper -> wrapper.isNull(Product::getSeckillActivityId).or().eq(Product::getSeckillActivityId, 0)));
                        .and(wrapper -> wrapper.isNull(Product::getProdType).or().eq(Product::getProdType, ProdType.PROD_TYPE_NORMAL)));
        return ResponseEntity.ok(products);
    }

    /**
     * 通过id使秒杀商品失效
     *
     * @param seckillId id
     * @return 是否删除成功
     */
    @SysLog("使秒杀失效信息")
    @PutMapping("/invalid/{seckillId}")
    public ResponseEntity<Void> invalidById(@PathVariable Long seckillId) {
        Seckill seckill = seckillService.getSeckillById(seckillId);
        if (!SecurityUtils.getShopUser().getShopId().equals(seckill.getShopId())) {
            throw new MaoshiShopBindException(MaoshiHttpStatus.UNAUTHORIZED);
        }
        seckillService.invalidById(seckill);

        productService.removeProductCacheByProdId(seckill.getProdId());
        seckillSkuService.removeSeckillSkuCacheBySeckillId(seckill.getSeckillId());
        seckillService.removeSeckillCacheById(seckill.getSeckillId());
        return ResponseEntity.ok().build();
    }

    /**
     * 通过id删除秒杀信息
     *
     * @param seckillId id
     * @return 是否删除成功
     */
    @SysLog("删除秒杀信息")
    @DeleteMapping("/{seckillId}")
    public ResponseEntity<Void> removeById(@PathVariable Long seckillId) {
        Seckill seckill = seckillService.getSeckillById(seckillId);

        if (!Objects.equals(0, seckill.getStatus())) {
            throw new MaoshiShopBindException("秒杀活动未失效，无法删除");
        }
        seckill.setIsDelete(1);
        seckillService.updateById(seckill);
        seckillSkuService.removeSeckillSkuCacheBySeckillId(seckill.getSeckillId());
        return ResponseEntity.ok().build();
    }

    /**
     * 通过活动id获取下线信息
     */
    @GetMapping("/getOfflineHandleEventBySeckillId/{seckillId}")
    public ResponseEntity<OfflineHandleEvent> getOfflineHandleEventBySeckillId(@PathVariable("seckillId") Long seckillId) {
        OfflineHandleEvent offlineHandleEvent = offlineHandleEventService.getProcessingEventByHandleTypeAndHandleId(OfflineHandleEventType.SECKILL.getValue(), seckillId);
        return ResponseEntity.ok(offlineHandleEvent);
    }

    /**
     * 违规商品提交审核
     */
    @PostMapping("/auditApply")
    public ResponseEntity<Void> auditApply(@RequestBody OfflineHandleEventAuditParam offlineHandleEventAuditParam) {
        Seckill seckill = seckillService.getSeckillById(offlineHandleEventAuditParam.getHandleId());
        if (seckill == null) {
            throw new MaoshiShopBindException("未找到该秒杀活动信息");
        }
        seckillService.auditApply(offlineHandleEventAuditParam.getEventId(), offlineHandleEventAuditParam.getHandleId(), offlineHandleEventAuditParam.getReapplyReason());

        // 移除缓存
        seckillService.removeSeckillCacheById(seckill.getSeckillId());
        return ResponseEntity.ok().build();
    }


}
